package org.ricks.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import java.net.InetSocketAddress;
import java.util.zip.CRC32;

/**
 * @Author ricks [chenwei]
 * @Version [v1.0]
 * @CreateTime 2024-06-20   20:10
 * @Description TODO
 */
public class NetutilsServerUtils {

    private static final ThreadLocal<NetutilsServerUtils.CrcInfo> crcInfo = new ThreadLocal<NetutilsServerUtils.CrcInfo>() {
        protected NetutilsServerUtils.CrcInfo initialValue() {
            return NetutilsServerUtils.CrcInfo.create(0);
        }
    };

    public NetutilsServerUtils() {
    }

    public void unload() {
        crcInfo.remove();
    }

    public static int uniqueHash(String str) {
        int h = 0;

        for(int i = 0; i < str.length(); ++i) {
            h = 31 * h + str.charAt(i);
        }

        return h;
    }

    public static long getSum(ByteBuf byteBuf, int offset, int len) {
        NetutilsServerUtils.CrcInfo info = (NetutilsServerUtils.CrcInfo)crcInfo.get();
        if (info.cache.length < len) {
            info.cache = new byte[len];
        }

        int beforeReadIndex = byteBuf.readerIndex();
        int beforeWriteIndex = byteBuf.writerIndex();
        byteBuf.readerIndex(offset);
        byteBuf.writerIndex(offset + len);

        long var6;
        try {
            byteBuf.readBytes(info.cache, 0, len);
            info.crc32.reset();
            info.crc32.update(info.cache, 0, len);
            var6 = info.crc32.getValue();
        } finally {
            byteBuf.readerIndex(beforeReadIndex);
            byteBuf.writerIndex(beforeWriteIndex);
        }

        return var6;
    }

    public static String getIp(Channel channel) {
        try {
            InetSocketAddress ipSocket = (InetSocketAddress)channel.remoteAddress();
            String clientIp = ipSocket.getAddress().getHostAddress();
            return clientIp == null ? "" : clientIp;
        } catch (Exception var3) {
            return "";
        }
    }

    private static class CrcInfo {
        private byte[] cache;
        private CRC32 crc32 = new CRC32();

        private CrcInfo() {
        }

        private static NetutilsServerUtils.CrcInfo create(int maxByteNum) {
            NetutilsServerUtils.CrcInfo info = new NetutilsServerUtils.CrcInfo();
            info.cache = new byte[maxByteNum];
            return info;
        }
    }
}
